// dao/distributionDao.js
const db = require("../config/db");

module.exports = {
  async getAll() {
    const [rows] = await db.execute(`
      SELECT * FROM distributors ORDER BY id DESC
    `);
    return rows;
  },

  async getById(id) {
    const [rows] = await db.execute(`SELECT * FROM distributors WHERE id = ?`, [
      id,
    ]);
    return rows[0];
  },

  async updatePayout(id, amount) {
    await db.execute(
      `UPDATE distributors
      SET pending_amount = 0,
          paid_amount = paid_amount + ?,
          status = 'paid',
          updated_at = NOW()
      WHERE id = ?`,
      [amount, id]
    );
  },

  async insertPayHistory(distributorId, amount) {
    await db.execute(
      `INSERT INTO pay_history (distributor_id, amount, time, remark)
      VALUES (?, ?, NOW(), '')`,
      [distributorId, amount]
    );
  },
  async getPayHistoryByDistributorId(distributorId) {
    const [rows] = await db.execute(
      `SELECT * FROM pay_history WHERE distributor_id = ? ORDER BY time DESC`,
      [distributorId]
    );
    return rows;
  },
};
